var masterCm;
var subCm;
var addWin;
var pbsocialItemWin;
//新增客户社保模板下面grid用到的store
var newStore2;
var deletedJson = [];
Ext.onReady(function() {

pbsocialItemWin = pbsocialitemsWin();
	newStore2 = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : 'customTemplateAction!queryCsTemplateDetailByFilter.action'
		}),
		reader : new Ext.data.JsonReader({
					root : 'beanList',
					id : "socialItemId"
				}, [{
						name : 'subSocialSecurityId',
						mapping : 'subSocialSecurityId'
					},{
						name : 'socialItemId',
						mapping : 'socialItemId'
					}, {
						name : 'socialItemName',
						mapping : 'socialItemName'
					}, {
						name : 'socialTypeId',
						mapping : 'socialTypeId'
					}, {
						name : 'socialTypeName',
						mapping : 'socialTypeName'
					}, {
						name : 'personBaseValue',
						mapping : 'personBaseValue'
					}, {
						name : 'personRate',
						mapping : 'personRate'
					}, {
						name : 'companyBaseValue',
						mapping : 'companyBaseValue'
					}, {
						name : 'companyRate',
						mapping : 'companyRate'
					}, {
						name : 'personAdd',
						mapping : 'personAdd'
					}, {
						name : 'companyAdd',
						mapping : 'companyAdd'
					}])
			});

	function buildSubCm() {
		subCm = new Ext.grid.ColumnModel([
				new Ext.grid.CheckboxSelectionModel(),{
					header : '社保项目名称',
					dataIndex : 'socialItemName',
					width : 100
				}, {
					header : '所属类别',
					dataIndex : 'socialTypeName',
					width : 100
				}, {
					header : '个人基数',
					dataIndex : 'personBaseValue',
					width : 100,
					editor : new Ext.form.TextField({})
				}, {
					header : '企业基数',
					dataIndex : 'companyBaseValue',
					width : 100,
					editor : new Ext.form.TextField({})
				}, {
					header : '个人比例',
					dataIndex : 'personRate',
					width : 100,
					editor : new Ext.form.TextField({})
				}, {
					header : '企业比例',
					dataIndex : 'companyRate',
					width : 100,
					editor : new Ext.form.TextField({})

				}, {
					header : '个人附加金额',
					dataIndex : 'personAdd',
					width : 100
				}, {
					header : '企业附加金额',
					dataIndex : 'companyAdd',
					width : 100
				}]);
		return subCm;
	}
	var subGrid = new Ext.grid.EditorGridPanel({
		id : "commsocial_master_grid1",
		cm : buildSubCm(),
		sm : new Ext.grid.CheckboxSelectionModel(),
		height : 200,
		width : 900,
		autoScroll : true,
		viewConfig : {
			width : 800,
			autoScroll : true
		},
		loadMask : true,
		loadMask : {
			msg : '正在加载数据...'
		},
		frame : true,
		clicksToEdit : 1,
		store : newStore2
		});
	var addPanel1 = new Ext.form.FormPanel({
				frame : true,
				id : 'addPanelForm1',
				bodyStyle : 'padding:5px 5px 0',
				autoDestroy : false,
				width : 900,
				height : 200,
				buttonAlign : 'right',
				items : [{
							layout : 'column',
							items : [{
										columnWidth : 0.0001,
										layout : 'form',
										items : [{
													xtype : 'hidden',
													name : 'csSocial.template_id',
													id : 'template_id'
												}]
									},{
										columnWidth : 0.4999,
										layout : 'form',
										items : [{
													layout : 'form',
													xtype : 'label',
													text : '客户中文名称：'+session_companyName
												}]
									}, {
										columnWidth : .5,
										layout : 'form',
										items : [ {
													xtype : 'textfield',
													fieldLabel : '模板名称',
													name : 'csSocial.name',
													id : 'name',
													allowBlank : false,
													blankText : '模板名称不能为空',
													emptyText : '请输入模板名称',
													anchor : '90%'
												}

										]
									}, {
										columnWidth : 1,
										layout : 'form',
										items : [{
													xtype : "textarea",
													fieldLabel : "说明",
													height : 100,
													width : 750,
													name : "csSocial.description",
													id : "description"
												}]
									}]
						}],
				buttons : [{
							text : '保存',
							id : 'continue',
							handler : function() {
								/**********************begin**************/
							if (Ext.getCmp('addPanelForm1').getForm().isValid()) {
								var templateId = Ext.getCmp('addPanelForm1').form.findField("template_id");
								var urlAdd = "";
								var paras={};
								if (templateId.getValue() == '') {
									//判断推荐模板名是否重复-结束
									urlAdd = 'customTemplateAction!insertCsSocial.action';// 新增推荐模板的action
									//2009.09.15 luli INS START
									var addJson=[];
									var recordLength = newStore2.getCount();
									var rs = newStore2.getRange(0,recordLength);
									for (var i = 0;i < recordLength ; i++){
										if (rs[i].data.subSocialSecurityId == undefined) {
											addJson.push(rs[i].data);
										}else{
											modifJson.push(rs[i].data);
										}
									};
									paras.adds=Ext.encode(addJson);
									//2009.09.15 luli INS END
									/*var add = newStore2.getRange(0,newStore2.getTotalCount()).slice(0);
									var addArray = [];
									//将EditorGird数据转换成JSON
									Ext.each(add,function(item){
										addArray.push(item.data);
									});
									paras.adds=Ext.encode(addArray);*/
								} else {
									urlAdd = 'customTemplateAction!updateCsSocial.action';// 更新推荐模板的action
									var addJson=[];
									var modifJson=[];
									var rs = newStore2.getRange(0,newStore2.getCount());
									var recordLength = newStore2.getCount();
									for (var i = 0;i < recordLength ; i++){
										if (rs[i].data.subSocialSecurityId == undefined) {
											addJson.push(rs[i].data);
										}else{
											modifJson.push(rs[i].data);
										}
									};
									paras.adds=Ext.encode(addJson);
									paras.modifs=Ext.encode(modifJson);
									paras.deleted=Ext.encode(deletedJson);
								}
								Ext.getCmp('addPanelForm1').getForm().submit({
											url : urlAdd,
											params:paras,
											success : function(from, action) {
												deletedJson=[];
												Ext.Msg.alert('提示', '操作客户社保模板失败!');
											},
											failure : function(form, action) {
												conditionStore.on('beforeload', function() {
													conditionStore.baseParams = {
														'filter.templateName' : Ext.getCmp('filter_templateName').getValue()==null?"":Ext.getCmp('filter_templateName').getValue(),
														'filter.socialItemName' : Ext.getCmp('filter_socialItemName').getValue()==null?"":Ext.getCmp('filter_socialItemName').getValue()
													}
												});
												conditionStore.load();
												newStore2.removeAll();
												deletedJson=[];
												addWin.hide();
											},
											waitMsg : '正在保存数据，稍后...'
										});

							} else {
								Ext.Msg.alert('提示', '请确认信息是否填写完整!');
							}
						}
						/**********************end**************/
						}, {
							text : '取消',
							id : 'cancel',
							handler : function() {
								newStore2.removeAll();
								addWin.hide();
							}
						}, {
							text : '新增子项',
							id : 'addSub',
							handler : function() {
								pbsocialItemWin.show();
							}
						}, {
							text : '删除子项',
							id : 'deleteSub',
							handler : function() {
								var recordLength = subGrid.getSelectionModel().getSelections().length;
								if (recordLength > 0) {
									Ext.MessageBox.confirm('确认删除', '你确认要删除' + recordLength + '条数据吗?', function(btn) {
										if (btn == "yes") {
											var rs = subGrid.getSelectionModel().getSelections();
											for (var i = 0;i < recordLength ; i++){
												if (rs[i].data.subSocialSecurityId != "") {
													deletedJson.push(rs[i].data);
												}
												newStore2.remove(newStore2.getById(rs[i].id));
											};
										}
									});
								} else {
									Ext.Msg.alert('提示', '请选择要添加的数据项!');
								}
							}
						}]
			});

	addWin = new Ext.Window({
				modal : true,
				buttonalign : 'right',
				closable : true,
				draggable : true,
				closeAction : 'hide',
				width : 910,
				height : 450,
				top : 10,
				region : 'center',
				plain : true,
				items : [addPanel1, subGrid],
				title : '模板信息',
				listeners : {
					"beforedestroy" : function(obj) {
						// obj.hide();
						return true;
					},
					"beforeshow" : function(obj) {
						//deletedJson = [];
						return true;
					},
					"beforehide" : function(obj) {
						addPanel1.getForm().reset();
						// conditionStore.loadData(Ext.util.JSON.decode("[]"),
						// false);
						// conditionStore.load();
						return true;
					}
				}

			});
	/**
	 * 主页面查询结果列
	 */
	function buildMasterCm() {
		masterCm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
				new Ext.grid.CheckboxSelectionModel(), 
				{
					header : 'ID',
					dataIndex : 'templateId',
					width : 80,
					hidden:true
				}, {
					header : '模板名称',
					dataIndex : 'templateName',
					width : 150
				}, {
					header : '模板细项数量',
					dataIndex : 'templateDetailCount',
					width : 150
				}, {
					header : '雇员数量',
					hidden : true,
					dataIndex : 'employeeCount',
					width : 150
				}, {
					header : '说明',
					dataIndex : 'memo',
					width : 150
				}]);
		return masterCm;
	}
	/**
	 * 主页面查询结果
	 */
	var conditionStore = new Ext.data.Store({
		url : 'customTemplateAction!query.action',
		reader : new Ext.data.JsonReader({
			root : 'result.result',
			id : 'template_id',
			totalProperty : 'result.totalCount'
			}, [{
					name : 'templateId',
					mapping : 'template_id'
				}, {
					name : 'templateName',
					mapping : 'name'
				}, {
					name : 'templateDetailCount',
					mapping : 'templateDetailCount'
				}, {
					name : 'employeeCount',
					mapping : 'employeeCount'
				}, {
					name : 'memo',
					mapping : 'description'
				}
			]
		)
	});

	var conditionForm = new Ext.form.FormPanel({
				// labelAlign: 'top',
				frame : true,
				title : '查询条件',
				id : 'conditionForm',
				bodyStyle : 'padding:5px 5px 0',
				layout : 'column',
				
				buttonAlign : 'right',
				items : [{
							layout : 'column',
							columnWidth : 1,
							items : [{
										columnWidth : 1,
										layout : 'form',
										items : [{
													layout : 'form',
													xtype : 'label',
													text : '客户中文名称：'+session_companyName
												}]
									}, {
										columnWidth : 0.5,
										layout : 'form',
										items : [{
													xtype : 'textfield',
													fieldLabel : '模板名称',
													name : 'filter.templateName',
													id : 'filter_templateName',
													anchor : '90%',
													emptyText : ''
												}]
									}, {
										columnWidth : 0.5,
										layout : 'form',
										items : [{
													xtype : 'textfield',
													fieldLabel : '社保项目名称',
													name : 'masFilter.socialItemName',
													id : 'filter_socialItemName',
													anchor : '90%',
													emptyText : ''
												}]
									}]
						}],
				buttons : [{
							xtype : 'button',
							text : '查询',
							handler : function() {
								conditionStore.on('beforeload', function() {
									conditionStore.baseParams = {
										'filter.templateName' : Ext.getCmp('filter_templateName').getValue()==null?"":Ext.getCmp('filter_templateName').getValue(),
										'filter.socialItemName' : Ext.getCmp('filter_socialItemName').getValue()==null?"":Ext.getCmp('filter_socialItemName').getValue()
									}
								});
								conditionStore.load();
							}
						}, {
							xtype : 'button',
							text : '新增',
							handler : function() {
								addWin.show();
							}
						}, {
							xtype : 'button',
							text : '删除',
							handler : function() {
								/**********kaishi*******/
								var recordLength = grid.getSelectionModel().getSelections().length;
								if (recordLength > 0) {
									Ext.MessageBox.confirm('确认删除', '你确认要删除' + recordLength + '条数据吗?', function(btn) {
												if (btn == "yes") {
													var deleteId = [];
													var rs = grid.getSelectionModel().getSelections();
													for (var i = 0; i < recordLength; i++) {
														var templateId = rs[i].data.templateId;
														deleteId.push(templateId);
													}
													Ext.Ajax.request({
														url : 'customTemplateAction!deleteCsSocialById.action',
														params : {
															"csSocial.ids" : deleteId.join(",")
														},
														success : function(response, options) {
															conditionStore.on('beforeload', function() {
																conditionStore.baseParams = {
																	'filter.templateName' : Ext.getCmp('filter_templateName').getValue()==null?"":Ext.getCmp('filter_templateName').getValue(),
																	'filter.socialItemName' : Ext.getCmp('filter_socialItemName').getValue()==null?"":Ext.getCmp('filter_socialItemName').getValue()
																}
															});
															conditionStore.load();
														}
													});
												}
											});
								} else {
									Ext.Msg.alert('提示', '请选择要删除的数据项!');
								}
								/**********结束*******/
							}
						}]
			});
	conditionForm.render(Ext.getBody());
	var grid = new Ext.grid.GridPanel({
		id : "master_grid",
		name : 'adf',
		cm : buildMasterCm(),
		sm : new Ext.grid.CheckboxSelectionModel(),
		store : conditionStore,
		height: document.body.clientHeight-Ext.getCmp('conditionForm').getInnerHeight()-Ext.getCmp('conditionForm').getFrameHeight(),
		
		loadMask : true,
		loadMask : {
			msg : '正在加载数据...'
		},
		frame : true,
		clicksToEdit : 1,
		bbar : new Ext.PagingToolbar({
			pageSize : pageSize,
			store : conditionStore,
			displayInfo : true,
			dispalyMsg : '显示第{0}条到{1}条记录，一共{2}条',
			emptyMsg : '没有记录'
		})
	});
	grid.addListener('rowdblclick', rowdblclickFn);
	conditionStore.load();
	grid.render(Ext.getBody());
});
function rowdblclickFn(grid, rowIndex, e) {
	Ext.Ajax.request({
		url:"customTemplateAction!retrieveEntity.action",
		params : {
			"csSocial.template_id" : grid.getStore().getAt(rowIndex).get('templateId')
		},
		method:"post",
		success: function(response,options){
			var responseTextValue = Ext.util.JSON.decode(response.responseText);
			addWin.show();
			Ext.getCmp('addPanelForm1').getForm().setValues(responseTextValue.csSocial);
			
			newStore2.proxy = new Ext.data.HttpProxy({
				url : 'customTemplateAction!queryCsTemplateDetailByFilter.action?templateId='+responseTextValue.csSocial.template_id
			});
			newStore2.load();
		}	
	});
}